package com.config.sharding.stock.circulation.complex;

import com.config.ShardingDictionaries;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author: create by God of SJF
 * @version: v1.0
 * @description: com.config
 * @date:2021/9/13
 */
@Component
public class StockDBShardingRule extends ShardingDictionaries implements ComplexKeysShardingAlgorithm<String> {
    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<String> complexKeysShardingValue) {
//        System.out.println("==============");
        String tableIndex = getIndex(complexKeysShardingValue);
        List<String> returnSharding = new ArrayList<>();
        String s = "stock"+ tableIndex;
        returnSharding.add(s);
        return returnSharding;
    }


    public String getIndex(ComplexKeysShardingValue<String> complexKeysShardingValue) {
        List<String> list = (List<String>) complexKeysShardingValue.getColumnNameAndShardingValuesMap().get("_barcode_content");
        String finalMap = null;
        String barcodeDirect = list.get(0);
        String first = barcodeDirect.substring(barcodeDirect.length() - 1, barcodeDirect.length());
        String firstKey = super.key(first);
        StringBuilder sb = new StringBuilder();
        sb.append(firstKey);
        finalMap = sb.toString();
        return finalMap;
    }
}
